<?php
/**
 * | ---------------------------------------------------------------------------------------------------
 * | Author：johnxu <fsyzxz@163.com>.
 * | ---------------------------------------------------------------------------------------------------
 * | Home: https://www.johnxu.net.
 * | ---------------------------------------------------------------------------------------------------
 * | Data: 2019-03-20
 * | ---------------------------------------------------------------------------------------------------
 * | Desc: 客服初始化操作
 * | ---------------------------------------------------------------------------------------------------
 */

namespace app\service\websocket\handler\drivers;

use app\admin\model\Users;
use app\service\websocket\handler\Driver;
use think\Db;

class Service extends Driver
{
    protected function getType()
    {
        return 'connect';
    }

    protected function getToInfo()
    {
        return [
            'fd' => $this->getFromInfo()['fd']
        ];
    }

    protected function intercept( \swoole_websocket_server $server, $fd )
    {
        // 处理是否登录
        if ( !isset( $this->data['token'] ) || empty( $this->data['token'] ) )
        {
            $server->push( $fd, $this->jsonEncode( [ 'type' => 'error', 'message' => '请登录后再试' ] ) );

            return false;
        }
        else
        {
            // 判断登录是否过期
            $tokenInfo = $this->getTokenInfo( $this->data['token'] );
            if ( !$tokenInfo )
            {
                $server->push( $fd, $this->jsonEncode( [ 'type' => 'error', 'message' => '登录过期，请重新登录' ] ) );

                return false;
            }
            else
            {
                // 查询登录用户的信息，返回给前台保存
                $kefuInfo   = $this->getUser( [ 'id' => $tokenInfo['user_id'] ] );
                $this->data = [
                    'uid'      => $kefuInfo['uid'],
                    'avatar'   => $kefuInfo['avatar'],
                    'token'    => $this->data['token'],
                    'nickname' => $kefuInfo['nickname'] ?: $kefuInfo['username'],
                    'time'     => time()
                ];
                $this->updateUser( [ 'fd' => $fd, 'state' => 'online' ], [ 'id' => $tokenInfo['user_id'] ] );

                return true;
            }
        }
    }
}